<?php

$sql_config=include "server_config/config.php";
$dbobj = new mysqli($sql_config['db_host'],$sql_config['db_user'],$sql_config['db_pw'],$sql_config['db_name'],$sql_config['db_port']);
if(!$dbobj->connect_error) echo"数据库连接成功！<br>";

// 指定上传目录
$target_dir = "skin/"; // 确保这个目录存在且有写权限

// 获取上传的文件信息
$file = $_FILES['file'];
$original_name = basename($file["name"]); // 获取原始文件名
$extension = pathinfo($original_name, PATHINFO_EXTENSION); // 获取文件扩展名



// 获取用户名
$username = $_POST['username']; // 替换为实际的用户名
$old_skin=$_POST['old_skin'];
$skins_type=$_POST['type'];

echo "$skins_type";


// 计算文件的 SHA-256 哈希
$hash = hash_file('sha256', $file['tmp_name']); // 计算上传文件的哈希值

// 获取当前日期和时间
$current_date = date("YmdHis"); // 格式：YYYYMMDD_HHMMSS

// 使用哈希值和当前日期命名文件
$new_name = $hash  . $current_date ; // 保留 .png 后缀
$new_full_name = $new_name . ".png";

echo "即将上传".$new_full_name;



$target_file = $target_dir . $new_full_name;


// 检查文件类型
if (strtolower($extension) == 'png') {

        // 检查是否为有效上传
    if (move_uploaded_file($file["tmp_name"], $target_file)) {
        echo "文件已成功上传: " . htmlspecialchars($new_full_name);

        $skins_type=intval($skins_type);
        echo "ttt";
        echo $skins_type;
        echo "ttt";
        $stmt="";
        switch($skins_type)
        {
            case 1:
            {
                $stmt = $dbobj->prepare("UPDATE mc_skin_con SET skins_default = ? WHERE username = ?");
                break;
            }
            case 2:
                {
                    $stmt = $dbobj->prepare("UPDATE mc_skin_con SET skins_slim = ? WHERE username = ?");
                    break;
                }
            case 3:
                {
                    $stmt = $dbobj->prepare("UPDATE mc_skin_con SET skins_cape = ? WHERE username = ?");
                    break;
                }
            case 4:
                {
                    $stmt = $dbobj->prepare("UPDATE mc_skin_con SET skins_elytra = ? WHERE username = ?");
                    break;
                }
        }
        
        
        if ($stmt === false) {
            echo "准备语句失败: " . $dbobj->error;
        }
        $stmt->bind_param("ss",$new_name, $username);
        $stmt->execute();
        $stmt->close();


        $delete_path="skin/". $old_skin .".png";
        if ($old_skin!=null && file_exists($delete_path)) 
        {
            

            if (unlink($delete_path)) 
            {
                echo "已成功删除文件: " . htmlspecialchars($delete_path);
            } 
            else 
            {
                echo "删除文件失败。";
            }
        } 
        else 
        {
            echo "文件不存在: " . htmlspecialchars($delete_path);
        }

    } else {
        echo "上传失败。";
    }



}
else
{
    echo "文件后缀名错误！";
}





$change_code=$_POST['change_code'];


// 关闭数据库连接
$dbobj->close();
header("Location:change_page.php?username={$username}&change_code={$change_code}");



?>
